var layer = require('layer');
var users = require('./users');
var userTpl = require('../../views/users');
var tpl = require('../../views/assign');
var template = require('template');
var request = require('request');
var select = require('{pub}/select');
var data = require('{pub}/data');
var util = require('util');
var json = require('{js}/polyfill/json');

return function(e, elem){
    var that = this;

    if(!that.datagrid.list.length){
        layer.alert('当前企业没有需要分配权限的帐套');
        return false
    }

    data.set('empList');

    var _layer = layer.form({
        content:template.render.call(tpl, tpl.main, {
            list:list,
            accounts:that.datagrid.list
        }),
        title:'分配权限',
        width:450,
        scrollbar:true,
        ajax:{
            url:'account/updateAuth',
            type:'PUT'
        },
        events:{
            'click .user i':function(e, elem){
                elem.parent().remove();
                _layer.resize();
            },
            'click .j-add':function(){
                require('./adduser').call(this, e, elem, _layer)
            }
        },
        onInit:function(self){
            users(self);
            self.element.find('select').imitSelect({
                callback:function(ele){
                    request.get('account/getAhthInfo', {id:ele.val()}, {
                        200:function(res){
                            self.element.find('.content').html(template.render.call(tpl, tpl.body, {list:res.data.account.roleList}))
                            _layer.resize();
                        }
                    }, self)
                }
            })
            self.resize();
        },
        getData:function(self, form){
            var data = util.getData(form, '.choose-usersbox', 'roleEmpList').result;
            data.roleEmpList = json.stringify(data.roleEmpList);
            data.id = data.accountid;
            delete data.accountid;
            return data
        },
        onSuccess:function(self, res){
            if(res.status == '200'){
                layer.message();
                self.destroy()
            }
        }
    })
}